import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.hub import load_state_dict_from_url

class ResNet(nn.Module):
    def __init__(self, block, layers, output_stride):
        super(ResNet, self).__init__()
        self.in_channels = 64
        blocks = [1, 2, 4]  # ???
        if output_stride == 16:
            strides = [1, 2, 2, 1]
            dilations = [1, 1, 1, 2]
        elif output_stride == 8:
            strides = [1, 2, 1, 1]
            dilations = [1, 1, 2, 4]
        else:
            raise NotImplementedError
        self.conv1 = nn.Conv2d(3, self.in_channels, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_channels)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        # self.conv_layers=[]
        self.layer1 = self._make_layer(block, 64, layers[0], stride=strides[0], dilation=dilations[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=strides[1], dilation=dilations[1])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=strides[2], dilation=dilations[2])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], blocks=blocks)

        # initialize weights
        # initialize weights
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, filters_nums, block_num, stride=1, dilation=1, blocks=False):
        # As the channel num of conv1 == filters_nums of conv2
        downsample = None
        if stride != 1 or self.in_channels != filters_nums * block.expansion:
            # 需要调整维度
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channels, filters_nums * block.expansion, kernel_size=1, stride=stride, bias=False),
                # 同时调整spatial(H x W))和channel两个方向
                nn.BatchNorm2d(filters_nums * block.expansion)
            )
        layers = []
        if not blocks:
            layers.append(block(self.in_channels, filters_nums, stride=stride, downsample=downsample,dilation=dilation))  # 第一个block单独处理
            self.in_channels = filters_nums * block.expansion  # 记录layerN的channel变化，具体请看ppt resnet表格
            for _ in range(1, block_num):  # 从1开始循环，因为第一个模块前面已经单独处理
                layers.append(block(self.in_channels, filters_nums, dilation=dilation))
        else:
            layers.append(block(self.in_channels, filters_nums, stride, dilation=blocks[0] * dilation,
                                downsample=downsample))
            self.in_channels = filters_nums * block.expansion
            for i in range(1, block_num):
                layers.append(block(self.in_channels, filters_nums, stride=1,
                                    dilation=blocks[i] * dilation))
        return nn.Sequential(*layers)  # 使用Sequential层组合blocks，形成stage。如果layers=[2,3,4]，那么*layers=？

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        low_level_feat = x

        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        return x, low_level_feat


class BottleNeck(nn.Module):
    expansion = 4  # input_channels*4=output_channels=last_filters

    def __init__(self, in_channels, filters, stride=1, downsample=None, dilation=1):
        super(BottleNeck, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, filters, kernel_size=1, stride=1, bias=False)
        self.bn1 = nn.BatchNorm2d(filters)
        self.conv2 = nn.Conv2d(filters, filters, kernel_size=3, stride=stride, padding=dilation, bias=False,
                               dilation=dilation)
        self.bn2 = nn.BatchNorm2d(filters)
        self.conv3 = nn.Conv2d(filters, filters * self.expansion, kernel_size=1, stride=1, bias=False)
        self.bn3 = nn.BatchNorm2d(filters * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        initial_input = x
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)

        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu(x)

        x = self.conv3(x)
        x = self.bn3(x)
        if self.downsample:
            initial_input = self.downsample(initial_input)
        x += initial_input
        x = self.relu(x)
        return x


def _resnet(block, layers, output_stride):
    model = ResNet( block, layers, output_stride)
    # pretrain_dict = load_state_dict_from_url('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    #                                          progress=True)
    # model_dict = {}
    # state_dict = model.state_dict()
    # for k, v in pretrain_dict.items():
    #     if k in state_dict:
    #         model_dict[k] = v
    # state_dict.update(model_dict)
    # model.load_state_dict(state_dict)
    return model


def ResNet101(output_stride):
    r"""ResNet-50 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet(BottleNeck, [3, 4, 23, 3],output_stride)